import Util from "./util.js"

function select_save_folder(){
	let fileDialog = window.Application.FileDialog(Util.WPS_Enum.msoFileDialogFolderPicker)
	fileDialog.Title = "选择要保存的位置"
	fileDialog.Show()
	if(fileDialog.SelectedItems.Count == 1){
		return fileDialog.SelectedItems.Item(1)
	}else{
		return 
	}
}
// 导出图片
function save_one_pic(folder, picName){
	window.Application.ActiveSheet.Range('A1').Select()
	window.Application.ActiveSheet.UsedRange.CopyPicture(1, 2)
	window.Application.ActiveSheet.Range("ZZ99999").PasteSpecial()
    
	for(let i=1; i<=window.Application.ActiveSheet.Shapes.Count; i++){
        let pic = window.Application.ActiveSheet.Shapes.Item(i)
		if(pic.Type == Util.WPS_Enum.msoPicture){
//			picName = `${new Date().getTime()}`// 注意重名问题，重名会被覆盖
			var picPathName = `${folder}\\${picName}.jpg`
			pic.Copy()
			pic.SaveAsPicture(picPathName)
			pic.Delete()
			window.Application.ActiveSheet.Range('A1').Select()
			window.Application.CutCopyMode = false; // 清理剪切板状态
		}
	}
}

// // 导出一张图片
let signal_folder = ''
function start_save_to_picture(){
	if(!signal_folder){
		signal_folder = select_save_folder()
	}
	if(!signal_folder) return

	let filename = window.Application.InputBox("输入保存的图片名", "输入图片名",undefined, undefined,undefined, undefined, undefined, 2)
	if(filename){
		save_one_pic(signal_folder, filename)
        alert('导出完成')
	}
}

// // 批量导出图片
function start_save_to_picture_many(){
	
	let folder = select_save_folder()
	if(!folder) return
	
	let data_range = window.Application.InputBox("选择数据范围", "选择数据",undefined, undefined,undefined, undefined, undefined, 8)

	let filter_range = window.Application.InputBox("选择过滤项", "选择数据",undefined, undefined,undefined, undefined, undefined, 8)
	let filter_data = new Set()
	for (let i=1; i<=filter_range.Count;i++){
		filter_data.add(filter_range.Item(i).Value2)
	}
//	console.log(filter_range.Column)
// 	filter_data.forEach((value) => {
// //	  console.log(folder, value);
// 	  // 筛选要过滤的项
// 	  window.Application.ActiveSheet.Range(data_range.Address()).AutoFilter(filter_range.Column, value)
// 	  save_one_pic(folder, value)
	  
// 	})
	for (let value of filter_data) {
		window.Application.ActiveSheet.Range(data_range.Address()).AutoFilter(filter_range.Column, value)
		window.Application.ActiveWindow.ScrollRow = 1
		Util.sleep(1)
		save_one_pic(folder, value)
		
		
	}
	// 恢复所有筛选项
	window.Application.ActiveSheet.Range(data_range.Address()).AutoFilter(filter_range.Column)
	alert('导出完成')

}



function export_single_picture(){
    return start_save_to_picture()
}

function export_many_picture(){
    return start_save_to_picture_many()
}

export default {
    export_single_picture,
    export_many_picture
}